package com.iscreen.web;

import java.io.IOException;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iscreen.core.services.downloader.DownloadMessage;
import com.iscreen.core.trading.beans.TradingDataImporter;

/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	@EJB
	private TradingDataImporter tradingResultsHandler;

	
	@Resource(mappedName = "ConnectionFactory")
	private QueueConnectionFactory connectionFactory;

	@Resource(mappedName = "queue/downloadQueue")
	private Queue queue;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TestServlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	private void testJMS(HttpServletResponse response, String name)
			throws IOException
	{
		response.getWriter().append("hello " + name);
		QueueConnection connection;
		try
		{
			connection = connectionFactory.createQueueConnection();
			QueueSession session = connection.createQueueSession(false,
					Session.AUTO_ACKNOWLEDGE);
			QueueSender sender = session.createSender(queue);
			DownloadMessage downloadMessage = new DownloadMessage("http://www.google.com/","c:\\temp\\test.html");
			Message message = session.createObjectMessage(downloadMessage);
			sender.send(message);
		}
		catch (JMSException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
//		testJMS(response, "Adi");
		testTradingResults(response);
	}

	private void testTradingResults(HttpServletResponse response)
	{
		try
		{
			tradingResultsHandler.importDailyResults();
			response.getWriter().append("OK");
		}
		catch (Exception e)
		{
			try
			{
				response.getWriter().append("SHIT");
			}
			catch (IOException e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
	}

}
